<template>
  <div>
    <BookAddAlert :obj="tableOper" :getBook="getBook"></BookAddAlert>
    <BookImgAlert :obj="authorImg" :getBook="getBook" :alert="alert"></BookImgAlert>
    <BookEditAlert :obj="tableEdit" :getBook="getBook" :alert="alert"></BookEditAlert>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item label="书名">
					<el-input v-model="filters.name" size="small" placeholder="书名"></el-input>
				</el-form-item>
        <el-form-item label="作者">
            <el-select v-model="filters.bAuth" filterable size="small" placeholder="请选择" @change="authorChange">
                <el-option v-for="(item,index) in authors" :key="index" :label="item.bAuth" :value="item.cid"></el-option>
            </el-select>
        </el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
    <div class="table-box">
      <el-table
        :data="tableData"
        :border="true"
        size="small"
        :fit="true"
        :highlight-current-row="true"
        @select-all="selectAllFn"
        @select="selectClick"
        @selection-change="selectionChange"
        :height="tableHeight"
        v-loading="listLoading"
        style="width: 100%">
        <el-table-column type="selection" width="40" fixed="left"></el-table-column>
        <el-table-column type="index" align="center" label="序号" width="50" fixed="left"></el-table-column>
        <el-table-column prop="imgurl"  label="封面"  min-width="100">
          <template slot-scope="scope">
            <img class="tpdj" style="display:block;width:30px;margin:0 auto;" :src="base+(scope.row.imgurl)" @click="imgClick($event)"/>
          </template>
        </el-table-column>
        <el-table-column prop="bid" align="center" label="书id" width="120" sortable></el-table-column>
        <el-table-column prop="bName" align="center" label="书名" width="120" sortable></el-table-column>
        <el-table-column prop="bAuth" align="center" label="作者" width="100"></el-table-column>
        <el-table-column prop="cat" align="center" label="类型" min-width="100"></el-table-column>
        <el-table-column prop="subCateName" align="center" label="子类型" min-width="100"></el-table-column>
        <el-table-column prop="stateType" align="center" :formatter="formatter" label="更新状态" min-width="70"></el-table-column>
        <el-table-column prop="isVip" align="center" :formatter="formatter1" label="isVip" min-width="70"></el-table-column>
        <el-table-column prop="desc" label="简介" :show-overflow-tooltip="true" min-width="500"></el-table-column>
        <el-table-column prop="updateTitle" align="center" label="更新章节" :show-overflow-tooltip="true" min-width="200"></el-table-column>
        <el-table-column prop="updateTime" align="center" label="更新时间" min-width="150" sortable></el-table-column>
        <el-table-column prop="startTime" align="center" label="创建日期" width="150"  sortable></el-table-column>
        <el-table-column label="操作" width="230" fixed="right">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="updateImg(scope.$index,scope.row)">上传封面</el-button>
            <el-button size="mini" @click="edit(scope.$index,scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="remove(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block pagination" v-show="tableData.length>0">
        <div class="pagination-left">
          <el-button type="danger" size="small" v-show="selectAll" @click="removeAll">批量删除</el-button>
        </div>
        <el-pagination
          @current-change="currentChange"
          @size-change="sizeChange"
          :current-page="1"
          :page-sizes="[10,20,50,100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import config from '../config.js'
import BookAddAlert from './BookAddAlert.vue'
import BookImgAlert from './BookImgAlert.vue'
import BookEditAlert from './BookEditAlert.vue'
import api from '../api'

import {getTimes} from '../assets/js/com.js'
  export default{
    mounted(){
        //完成编译后更新表格的数据
        this.getBook();
        //窗口自动适应宽高
        this.rewindow();
        this.getAuthor();
    },
    methods:{
      //搜索作者选择
      authorChange(id){
        let obj=this.authors.find((item)=>{
          return item.cid==id;
        })
        this.filters.bAuthName=obj.bAuth;
      },
      //获取搜索的下来作者数据
      getAuthor(){
        api.$http("/system/getAllBookInfo",{},function(err,res){
          if(res.data.code==1){
            this.authors=res.data.info.authors;
            this.authors.unshift({cid:0,bAuth:"请选择"});
          }
        }.bind(this));
      },
      //获取书本函数
      getBook(){
        //显示加载中
        this.listLoading=true;
        //post
        let obj={};
        if(this.filters.bAuth==0){
          obj={
              search:this.filters.name,
              auth:"",
              pageSize:this.pageSize,
              currentPage:this.currentPage
          };
        }else{
          obj={
              search:this.filters.name,
              auth:this.filters.bAuthName,
              pageSize:this.pageSize,
              currentPage:this.currentPage
          };
        }
        //获取书籍
        api.$http("/system/getBooks",obj,function(err,res){
          if(err){
            this.alert('出错');
            return;
          }
          //console.log(res.data);
          //当前条件所有数据的数量
          this.total=res.data.count;
          if(res.data.code==1){
            //转换时间
            for(let val in res.data.info){
              res.data.info[val]['startTime']=getTimes(res.data.info[val]['startTime']);
              res.data.info[val]['updateTime']=getTimes(res.data.info[val]['updateTime']);
            }
            //把数据给数组
            this.tableData=res.data.info;
            //隐藏加载中
            this.listLoading=false;
            //
            if(this.tableData.length<1){
              this.tableHeight=100
            }else{
              this.rewindow();
            }
          }else{
              this.$message.error('获取数据失败');
          }
        }.bind(this));//绑定vue对象
      },
      //窗口自动适应
      rewindow(){
        let wh=window.innerHeight;
        this.tableHeight=wh-190;
        let tath=this;
        window.onresize=function(){
          let wh=window.innerHeight;
          tath.tableHeight=wh-190;
        }
      },
      //更新状态格式化
      formatter(row, column, cellValue){
          return cellValue=="T"?"连载":"完结";
      },
      //isvip格式化
      formatter1(row, column, cellValue){
          return cellValue==0?"否":"是";
      },
      //搜索
      getUsers(){
          this.getBook();
      },
      //新增
      handleAdd(){
        this.tableOper={      //对话框弹出默认
          title:"新增书籍",
          isShow:true,
          name:"",
          isvip:0,
          status:"E",
          cat:1,
          catName:"",
          subCate:1,
          subCateName:"",
          stateType:"T",
          bAuth:1000000001,
          authorName:"",
          desc:"",
          date:new Date()
        }
      },
      //提示函数
      alert(txt){
        this.$alert(txt, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            return true;
          }
        });
      },
      //图片预览
      imgClick(ev){
        this.$alert('<img style="margin:0 auto;display:block;" src="'+ev.target.src+'">', '图片预览', {
          dangerouslyUseHTMLString: true,
          callback:action=>{
            return true;
          }
        });
      },
      //上传封面
      updateImg(index,row){
        this.authorImg.bid=row.bid;
        this.authorImg.isShow=true;
      },
      //修改书籍
      edit(index,row){
          //console.log(row);
          this.tableEdit.row={
              bid:row.bid,
              name:row.bName,
              isvip:row.isVip,
              status:row.signStatus,
              cat:row.catId,
              catName:row.cat,
              subCate:row.subCateId,
              subCateName:row.subCateName,
              stateType:row.stateType,
              bAuth:row.cid,
              authorName:row.bAuth,
              desc:row.desc,
              date:new Date(row.startTime)
          };
          this.tableEdit.isShow=true;
      },
      //删除书籍
      remove(index,row){
          this.$confirm('是否删除该书籍?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.listLoading=true;
            api.$http("/system/removeBook",row,function(err,res){
              if(res.data.code==1){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.listLoading=false;
                this.getBook();
              }
            }.bind(this));
          }).catch(() => {
                   
          });
      },
      //批量删除
      removeAll(){
          var tath=this; 
          this.$confirm('是否批量删除这些书籍?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            tath.listLoading=true;
            (function bl(i){
              i++;
              if(i==tath.selection.length){
                  tath.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                  tath.listLoading=false;
                  tath.getBook();
                  return;
              }else{
                  api.$http("/system/removeBook",tath.selection[i],function(err,res){
                    if(res.data.code==1){
                        console.log(res.data.msg);
                        bl(i);
                    }else{
                      tath.$message({
                        type: 'warning',
                        message: '数据库操作出错'
                      });
                    }
                  });
              }
            })(-1);            
          }).catch(() => {
                return false;
          });
      },
      //全选
      selectAllFn(selection){
        this.selectionLength=selection.length;
        if(selection.length>0){
          this.selectAll=true;
        }else{
          this.selectAll=false;
        }
        this.selection=selection;
      },
      selectClick(selection,row){
        this.selection=selection;
      },
      //选择改变
      currentChange(currentPage){
          this.currentPage=currentPage;
          this.getBook();
      },
      //分页大小
      sizeChange(size){
        this.pageSize=size;
        this.currentPage=1;
        this.getBook();
      },
      //选中改变
      selectionChange(selection){
        this.selectionLength=selection.length;
        if(selection.length>0){
          this.selectAll=true;
        }else{
          this.selectAll=false;
        }
        this.selection=selection;
      }
    },
    //子组件
    components:{
      BookAddAlert,
      BookImgAlert,
      BookEditAlert
    },
    data(){
      return {
        tableHeight:300,  //表格默认高度
        selectAll:false,  //默认不选中全部
        base:config.base, //ip
        total:0,          //表格总数据量
        pageSize:10,      //分页每页默认10行
        currentPage:1,    //默认当前第一页
        selectionLength:0,//选中的行数
        listLoading:false,//加载中的状态
        tableData:[],    //表格数据
        filters:{        //搜索的条件
          name:"",
          bAuth:"",
          bAuthName:""
        },
        selection:[],
        authors:[],
        tableOper:{      //对话框弹出默认
          title:"新增书籍",
          isShow:false,
          name:"",
          isvip:0,
          status:"E",
          cat:1,
          catName:"",
          subCate:1,
          subCateName:"",
          stateType:"T",
          bAuth:1000000001,
          authorName:"",
          desc:"",
          date:new Date()
        },
        authorImg:{      
          title:"上传封面",
          isShow:false,
          bid:0
        },
        tableEdit:{
          title:"编辑书本",
          isShow:false,
          row:{
              name:"",
              isvip:0,
              status:"E",
              cat:0,
              catName:"",
              subCate:0,
              subCateName:"",
              stateType:"T",
              bAuth:"",
              authorName:"",
              desc:"",
              date:new Date()
          }
        }
      }
    }
  }
</script>
<style>
.el-button+.el-button{
  margin-left: 0px;
}
</style>



